/*
 * @Author: GY19531 418941369@qq.com
 * @Date: 2022-09-01 21:50:42
 * @LastEditors: GY19531 418941369@qq.com
 * @LastEditTime: 2022-09-09 11:07:08
 * @FilePath: \one-web\src\pages\RemindManage\mview\particularsModal.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { ChangeEvent, useEffect, useMemo, useState } from 'react';
import { getNotifyService } from '../services';
import {
  AutoComplete,
  Card,
  Col,
  Collapse,
  Descriptions,
  Drawer,
  Empty,
  Input,
  List,
  message,
  Progress,
  Row,
  Spin,
  Tooltip,
} from 'antd';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { SearchOutlined, EyeOutlined } from '@ant-design/icons';
import { getColorTextLoadMap } from '@/utils';
const { Panel } = Collapse;
import MyIcon from '@/components/MyIcon';
import detailStyle from '../common/index.less';
import { TypographyTitle } from '@/components/Typography';
import CronParser from 'cron-parser'; //npm包
import CronParse from '../common/parse-lib';
import moment from 'moment';
const dateMinute = 'YYYY-MM-DD HH:mm';
const DesItem = Descriptions.Item;
export default function ParticularsModal(props: any) {
  const [record, setrecord]: any = useState();
  const [renderArr, setRenderArr]: Array<any> = useState();
  const [tempArr, setTempArr]: any = useState([]);
  const getCallback = (res: any) => {
    console.log('查看详情数据', res);
    /**
     * @description: setrecord  保存展示数据的state*/
    setrecord(res?.obj);
    // 备忘录判断
    if (res?.obj?.notifyTypeName.split('||')[0] == '备忘录') {
      let arr = [];
      arr.push({ realName: res?.obj?.createrName, id: res?.obj?.id });
      setRenderArr(arr);
      message.success(res.msg);
      return;
    }

    /**
     * @description: setRenderArr  保存展示人的数组    不为null说明是提醒他人*/

    if (res?.obj?.expandDisplay !== null) {
      let { centreUserRows, joinCheckBoxKeys } = res?.obj?.expandDisplay;
      const arr = centreUserRows.filter((item: any, index: number) => {
        return joinCheckBoxKeys.includes(item?.id);
      });
      setRenderArr(arr);
    } else {
      let arr = [];
      arr.push({ realName: res?.obj?.createrName, id: res?.obj?.id });
      setRenderArr(arr);
    }
    console.log(res);
    message.success(res.msg);
  };
  /**
   * 详情搜索
   */
  const [infoSearchValue, setInfoSearchValue] = useState<string>('');
  /**
   * @description: 编辑
   * @return {*}
   */
  const { getNotifyLoading, getNotifyRun } = getNotifyService(getCallback);
  useEffect(() => {
    // console.log()
    getNotifyRun(props?.partid);
  }, [props?.partid]);
  useEffect(() => {
    if (record && record?.cronExpression) {
      const weekCron = record?.cronExpression.split(' ')[5];
      if (weekCron !== '?') {
        let arr = [];
        const interval = CronParser.parseExpression(String(record?.cronExpression).trim());
        for (let i = 0; i < 5; i++) {
          const temp = moment(interval.next().toString()).format(dateMinute);
          arr.push(temp);
        }
        setTempArr(arr);
      } else {
        const core: any = new CronParse();
        setTempArr(core.expressionChange(String(record?.cronExpression).trim()));
      }
    }
  }, [record?.cronExpression]);
  /**
   * 搜索框改变
   * @param e
   */
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    setInfoSearchValue(e.target.value);
  };
  /**
   * @description: 渲染字段方法
   * @return {*}
   */
  const renderNotifyStyle = (record: any) => {
    if (record === 0) {
      return '单次提醒';
    } else if (record === 1) {
      return '多次提醒';
    } else if (record === 2) {
      return '复杂提醒';
    }
  };
  /**
   * 处理搜索变色
   * @param dataName
   * @param icon
   * @returns
   */
  const searchChangeStyle = (dataName: string) => {
    const name = dataName;
    const nameLength = name?.length;
    const select = name?.search(infoSearchValue);
    const searchLength = infoSearchValue?.length;
    const afterStr = name?.slice(0, select);
    const selectStr = infoSearchValue;
    const beforeStr = name?.slice(select + searchLength, nameLength);
    const title =
      select > -1 && selectStr ? (
        <div>
          {afterStr}
          <span style={{ color: '#f50' }}>{selectStr}</span>
          {beforeStr}
        </div>
      ) : (
        <div>{dataName}</div>
      );
    return title;
  };
  // 搜索下拉菜单
  const autoOptionPosCard = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.realName?.includes(infoSearchValue)) {
          const name = item?.realName;
          const nameLength = name?.length;
          const select = name?.search(infoSearchValue);
          const searchLength = infoSearchValue?.length;
          const afterStr = name?.slice(0, select);
          const selectStr = infoSearchValue;
          const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: name,
            key: item?.id + 'RemindDetailUserID',
            label: (
              <div>
                <span>{afterStr}</span>
                <span style={{ color: '#f50' }}>{selectStr}</span>
                <span>{beforeStr}</span>
              </div>
            ),
          });
        }
      });
    };
    tileTreeData(renderArr);
    return option;
  }, [renderArr, infoSearchValue]);
  // 点击搜索
  const onAutoSelectPos = (value: string, option: any) => {
    const optionId = option?.key;
    setInfoSearchValue(value);
    setTimeout(() => {
      scrollToAnchor(optionId);
    }, 1000);
  };
  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + 'RemindDetailUserID');
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };
  const renderNotifyType = (item: any) => {
    const { color, colorText } = getColorTextLoadMap(item);
    return <span style={{ color }}>{colorText}</span>;
  };
  const renderHours = (item: number) => {
    return moment(item).format('HH 小时 mm 分 ss 秒');
  };
  return (
    <>
      <Drawer
        title="提醒详情"
        placement={'right'}
        closable={false}
        onClose={() => {
          props.onClose();
        }}
        open={props.drawer}
        key={'right'}
        getContainer={false}
        style={{ position: 'absolute' }}
        width={document.body.clientWidth * 0.47}
        headerStyle={{
          padding: '.5rem',
        }}
        bodyStyle={{
          padding: '5px 0px',
        }}
      >
        <Spin spinning={(record && record?.id && false) || getNotifyLoading}>
          <ScrollBarLayout
            style={{
              padding: '10px 15px',
            }}
          >
            <div className={detailStyle['detailDept']}>
              <div style={{ padding: '0px 0px 10px 0px' }}>
                <TypographyTitle
                  level={4}
                  style={{
                    margin: 0,
                  }}
                >
                  基本信息
                </TypographyTitle>
              </div>
              <Descriptions bordered size="small" column={4}>
                <DesItem
                  span={4}
                  label={
                    <span>
                      <MyIcon type="icon-shenhe" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;提醒内容
                    </span>
                  }
                >
                  {record && record?.notifyContent ? record?.notifyContent : '--'}
                </DesItem>
                <DesItem
                  span={4}
                  label={
                    <span>
                      <MyIcon type="icon-shenhe" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;提醒情况
                    </span>
                  }
                >
                  <Row>
                    <Col span={18}>
                      <Tooltip placement="top" title={`已执行 ${record?.notifyedCount} 次提醒`}>
                        <Progress
                          className="remind-progress"
                          percent={Math.floor((record?.notifyedCount / record?.notifyCount) * 100)}
                          size="small"
                          format={(percent) => `共计 ${record?.notifyCount} 次`}
                        />
                      </Tooltip>
                    </Col>
                    <Col span={7}></Col>
                  </Row>
                </DesItem>
                {/* <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon
                        type="icon-laiyuanqingkuang"
                        style={{ fontSize: '18px' }}
                      />
                      &nbsp;&nbsp;提醒情况
                    </span>
                  }
                >
                  <Row>
                    <Col span={18}>
                      <Tooltip
                        placement="top"
                        title={`已执行 ${record?.notifyedCount} 次提醒`}
                      >
                        <Progress
                          className="remind-progress"
                          percent={Math.floor(
                            (record?.notifyedCount / record?.notifyCount) * 100,
                          )}
                          size="small"
                          format={(percent) => `共计 ${record?.notifyCount} 次`}
                        />
                      </Tooltip>
                    </Col>
                    <Col span={7}></Col>
                  </Row>
                </DesItem> */}
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-responsibility" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;提醒方式
                    </span>
                  }
                >
                  {/* ?  */}
                  {record && record?.notifyStyle >= 0 ? renderNotifyStyle(record?.notifyStyle) : '--'}
                </DesItem>
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-leixing1" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;提醒类型
                    </span>
                  }
                >
                  {record && record?.notifyType ? renderNotifyType(record?.notifyTypeName) : '--'}
                </DesItem>

                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-weimingmingwenjianjia_lanmu" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;提醒间隔
                    </span>
                  }
                >
                  {record?.notifyInterval && record?.notifyInterval > 0
                    ? renderHours(record?.notifyInterval)
                    : record?.notifyInterval + ' 秒'}
                </DesItem>
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-kaishishijian" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;开始时间
                    </span>
                  }
                >
                  {record && record?.startTime ? `${record?.startTime}` : '--'}
                </DesItem>
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-jiezhishijian" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;结束时间
                    </span>
                  }
                >
                  {record && record?.endTime ? `${record?.endTime}` : '--'}
                </DesItem>
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-shijianxuanzeqi" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;最近提醒时间
                    </span>
                  }
                >
                  {record?.lastTime ? record?.lastTime : '--'}
                </DesItem>
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-chuangjiangongdan" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;工单类型
                    </span>
                  }
                >
                  {'--'}
                </DesItem>
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-hetongguanli-" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;工单详情
                    </span>
                  }
                >
                  {
                    <EyeOutlined
                      onClick={() => {
                        console.log('dianji');
                      }}
                    />
                  }
                </DesItem>
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-shouye" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;创建人
                    </span>
                  }
                >
                  {record && record?.createrName ? record?.createrName : '--'}
                </DesItem>
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-gangweitubiao" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;创建岗位
                    </span>
                  }
                >
                  {record && record?.createPositionName ? record?.createPositionName : '--'}
                </DesItem>
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-bumen" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;创建部门
                    </span>
                  }
                >
                  {record && record?.createDepartmentName ? record?.createDepartmentName : '--'}
                </DesItem>
                <DesItem
                  span={2}
                  label={
                    <span>
                      <MyIcon type="icon-gongsi" style={{ fontSize: '18px' }} />
                      &nbsp;&nbsp;创建公司
                    </span>
                  }
                >
                  {record && record?.createCompanyName ? record?.createCompanyName : '--'}
                </DesItem>
              </Descriptions>
            </div>
            {/* -----------------------------------------------------------------提醒人信息如下 */}
            <div style={{ padding: '15px 0px 10px' }}>
              <TypographyTitle
                level={4}
                style={{
                  margin: 0,
                }}
              >
                被提醒人
              </TypographyTitle>
            </div>
            <div className={detailStyle['remindInfoPostionStyle']}>
              <Card
                bordered
                title={
                  <>
                    <AutoComplete
                      style={{ width: '100%' }}
                      options={autoOptionPosCard}
                      notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                      onSelect={onAutoSelectPos}
                    >
                      <Input suffix={<SearchOutlined />} onChange={onInputChange} placeholder="请按名称搜索" allowClear={true} />
                    </AutoComplete>
                  </>
                }
              >
                <ScrollBarLayout
                  style={{
                    padding: '10px 10px',
                    maxHeight: document.body.clientHeight * 0.27,
                    minHeight: document.body.clientHeight * 0.27,
                  }}
                >
                  {renderArr && renderArr.length > 0 ? (
                    <div className={'detailPositionCard'}>
                      {renderArr &&
                        renderArr.map((item: any, index: number) => {
                          let receiveName: string = item?.realName ? item?.realName : '';
                          let showTitle = searchChangeStyle(receiveName);
                          return (
                            <div id={item?.id + 'RemindDetailUserID'} key={item?.id}>
                              <div className={'detailCardChildren'}>
                                <div>
                                  <MyIcon type={'icon-cluster'} />
                                </div>
                                <div>{showTitle}</div>
                              </div>
                            </div>
                          );
                        })}
                    </div>
                  ) : (
                    <>
                      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    </>
                  )}
                </ScrollBarLayout>
              </Card>
            </div>
            {record && record?.notifyStyle == '2' ? (
              <>
                <div style={{ padding: '15px 0px 10px' }}>
                  <TypographyTitle
                    level={4}
                    style={{
                      margin: 0,
                    }}
                  >
                    最近提醒
                  </TypographyTitle>
                </div>
                <div>
                  <Collapse accordion>
                    <Panel header="最近执行的5次" key="1">
                      <List
                        bordered
                        dataSource={tempArr}
                        renderItem={(item: any, index) => (
                          <List.Item>
                            最近的第{index + 1}次提醒:&nbsp;&nbsp;&nbsp;&nbsp;
                            {item}
                          </List.Item>
                        )}
                      />
                    </Panel>
                  </Collapse>
                </div>
              </>
            ) : null}
          </ScrollBarLayout>
        </Spin>
      </Drawer>
    </>
  );
}
